package 集合;

import com.alibaba.fastjson.JSON;

import java.util.*;

public class No49字母异位词分组 {

    /**
     * 给定一个字符串数组，将字母异位词组合在一起。字母异位词指字母相同，但排列不同的字符串。
     * 示例:
     * 输入: ["eat", "tea", "tan", "ate", "nat", "bat"]
     * 输出:
     * [
     *   ["ate","eat","tea"],
     *   ["nat","tan"],
     *   ["bat"]
     * ]
     */

    public static List<List<String>> groupAnagrams(String[] strs) {

        Map<String, ArrayList<String>> map=new HashMap<>();

        for(int i=0;i<strs.length;i++){

            char[] chars = strs[i].toCharArray();
            Arrays.sort(chars);
            String s = String.valueOf(chars);

            ArrayList<String> stringArrayList = map.get(s);

            if(stringArrayList==null){
                ArrayList<String> list = new ArrayList<>();
                list.add(strs[i]);
                map.put(s,list);
            }else{
                stringArrayList.add(strs[i]);
            }

        }

        List<List<String>> result=new ArrayList<>();

        for(String c:map.keySet()){
            ArrayList<String> stringArrayList = map.get(c);
            result.add(stringArrayList);
        }

        return result;
    }

    public static void main(String[] args) {

        String[] arr=new String[]{"eat", "tea", "tan", "ate", "nat", "bat"};

        List<List<String>> lists = groupAnagrams(arr);

        System.out.println(JSON.toJSONString(lists));

    }

}
